package me.shurufa.activities;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.Bind;
import me.shurufa.R;
import me.shurufa.model.AddDigestBean;
import me.shurufa.utils.BitmapUtils;
import me.shurufa.utils.Constants;
import me.shurufa.widget.cropimageview.CropImageView;
import me.shurufa.widget.smoothcamera.core.CameraManager;
import me.shurufa.widget.smoothcamera.view.CameraActivity;

/**
 * 作者 : andy
 * 日期 : 16/3/14 14:19
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 横屏裁切图片界面
 */
public class CropImageActivity extends BaseLandscapeActivity implements View.OnClickListener {

    private static final String ARGUMENT_IMAGE_PATH = "ARGUMENT_IMAGE_PATH";

    //@Bind(R.id.right_text)
    //TextView rightText;
    @Bind(R.id.iv_crop)
    CropImageView iv_crop;
    @Bind(R.id.btn_next)
    TextView btn_next;
    @Bind(R.id.btn_retake)
    TextView btn_retake;
    @Bind(R.id.ll_operate)
    LinearLayout ll_operate;

    @Bind(R.id.camera_back)
    ImageView camera_back;

    private String mImagePath;
    private AddDigestBean mAddDigestBean;
    private WindowManager wm;
    private int mReqWidth;
    private int mReqHeight;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_crop_image;
        super.onCreate(savedInstanceState);
        parseArguments();
        initUI();
        initListener();
    }

    /**
     * @param in
     * @param absImagePath 图片绝对路径
     */
    public static void initArguments(Intent in, String absImagePath, AddDigestBean addDigestBean) {
        in.putExtra(ARGUMENT_IMAGE_PATH, absImagePath);
        in.putExtra(Constants.ARG_ADD_DIGEST, addDigestBean);
    }

    private void parseArguments() {
        mImagePath = getIntent().getStringExtra(ARGUMENT_IMAGE_PATH);
        mAddDigestBean = (AddDigestBean) getIntent().getSerializableExtra(Constants.ARG_ADD_DIGEST);
    }

    private void initUI() {
        //rightText.setText(getString(R.string.next));
        //rightText.setOnClickListener(this);

        wm = getWindowManager();
        mReqWidth = wm.getDefaultDisplay().getWidth();
        mReqHeight = wm.getDefaultDisplay().getHeight();

        iv_crop.setCropMode(CropImageView.CropMode.RATIO_FREE);
        // 显示图片
        showImage();
    }

    private void initListener() {
        btn_next.setOnClickListener(this);
        btn_retake.setOnClickListener(this);
        camera_back.setOnClickListener(this);
        iv_crop.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        ll_operate.setVisibility(View.GONE);
                        break;
                    case MotionEvent.ACTION_UP:
                        ll_operate.setVisibility(View.VISIBLE);
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 显示图片
     */
    private void showImage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // final Bitmap bmp = BitmapUtils.getNormalSizeBitmap(CropImageActivity.this, mImagePath);
                final Bitmap bmp = BitmapUtils.decodeSampledBitmapFromFd(mImagePath, mReqWidth, mReqHeight);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        iv_crop.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                        iv_crop.setImageBitmap(bmp);
                        // iv_crop.setImageResource(R.drawable.bg_login);
                    }
                });
            }
        }).start();

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()){
            case R.id.right_text:
                    intent = new Intent(CropImageActivity.this, CameraActivity.class);
                    startActivity(intent);
                break;

            case R.id.btn_next:
                    onNext();
                break;

            case R.id.camera_back:
                finish();
                break;

            case R.id.btn_retake:
                checkCameraPermission();
                System.gc();
                finish();
                break;
        }
    }

    /**
     * 下一步跳转到新界面
     */
    private void onNext() {
        FileOutputStream fos = null;
        // 用于创建临时文件
        try {
            Bitmap bitmap = iv_crop.getCroppedBitmap();
            File file = File.createTempFile("DCIM", ".jpg");
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            //Intent intent = new Intent(this, BitmapTransformActivity.class);
            Intent intent = new Intent(this, BookDigiestPreviewActivity.class);
            BookDigiestPreviewActivity.initArguments(intent, file.getAbsolutePath(), mAddDigestBean);
            startActivity(intent);
            System.gc();
            finish();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 去相机界面
     */
    private void goCamera() {
        /* Intent in = new Intent(this, NewCameraActivity.class);
        startActivity(in);*/

        CameraManager.getInstance().openCamera(this, true);
    }

    private void checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if(checkCameraPermission != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constants.REQUEST_CAMERA);
                return;
            }else{
                goCamera();
            }
        } else {
            goCamera();
        }
    }

}
